<?php

namespace app\admin\controller\user\party;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Response;
use think\Db;
use think\Log;
use think\Loader;
use fast\Random;

/**
 * 党员信息
 *
 * @icon fa fa-circle-o
 */
class Partybranch extends Backend
{

    /**
     * Member模型对象
     * @var \app\admin\model\user\party\Partybranch
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\party\Partybranch;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $domain = $_SERVER['HTTP_HOST'];
        $url = $protocol . '://' . $domain;
        $site = config('site');
        $this->view->assign("party_member", $site['party_member']);
        $this->view->assign("url", $url);
    }



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // echo json_encode($where);
            if (isset($filter['type'])) {
                $list = $this->model
                    ->with(['user', 'userinfo'])
                    ->where('type', $filter['type'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            } else {
                $list = $this->model
                    ->with(['user', 'userinfo'])
                    ->where('type', '>', '1')
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }


            // foreach ($list as $row) {

            //     $row['image'] = empty($row['image']) ? '/assets/addons/classroom/img/noimage.jpg' : $row['image'];
            //     $row->getRelation('category')->visible(['name']);
            // }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail($id = '')
    {
        $data = $this->model
            ->with(['user', 'userinfo'])
            ->where($this->model->getTable() . '.id', $id)
            ->find();
        $data["school"] = model('app\admin\model\department\School')->where('id', $data['userinfo']['school'])->find();
        $data["college"] = model('app\admin\model\department\School')->where('id', $data['userinfo']['college'])->find();
        $data["system"] = model('app\admin\model\department\School')->where('id', $data['userinfo']['system'])->find();
        $this->view->assign("data", $data);

        return $this->view->fetch();
    }


    /**
     * 导入
     */
    public function import()
    {
        $this->relationSearch = true;
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params || empty($params['import_file_url'])) {
                $this->error('请上传 Excel 文件');
            }

            $filePath = ROOT_PATH . 'public' . $params['import_file_url'];
            if (!file_exists($filePath)) {
                $this->error('文件不存在');
            }

            try {
                $spreadsheet = IOFactory::load($filePath);
                $sheet = $spreadsheet->getActiveSheet();
                $data = $sheet->toArray();

                if (count($data) < 2) {
                    $this->error('Excel 数据为空或格式错误');
                }

                Db::startTrans();

                $insertData = [];
                $userinfoData = [];

                foreach ($data as $key => $row) {
                    if ($key == 0) continue;
                    if (empty($row[5])) continue;

                    $salt = Random::alnum();
                    $password = substr(trim($row[5]), -6);
                    $hashedPassword = md5(md5($password) . $salt);

                    $user = [
                        'username'    => trim($row[7]),
                        'nickname'    => trim($row[0]),
                        'password'    => $hashedPassword,
                        'salt'        => $salt,
                        'mobile'      => trim($row[3]),
                        'email'       => trim($row[4]),
                        'level'       => 1,
                        'gender'      => $row[1] == '男' ? 1 : 0,
                        'name'        => trim($row[0]),
                        'id_no'       => trim($row[5]),
                        'work_number' => trim($row[7]),
                        'is_student'  => $row[6] == '是' ? 1 : 0,
                        'createtime'  => time(),
                    ];
                    $user_info = Db::name('user')->where('username', trim($row[6]))->count();
                    if ($user_info == 0) {
                        $user_id = Db::name('user')->insertGetId($user);
                        if (!$user_id) throw new \Exception("用户 {$row[0]} 插入失败");

                        $partyMember = [
                            'user_id'            => $user_id,
                            'thee_department_id' => $params['area'],
                            'number'             => trim($row[8]),
                            'create_time'        => time(),
                        ];

                        $userinfo = [
                            'user_id'    => $user_id,
                            'name'       => trim($row[0]),
                            'work_number' => trim($row[7]),
                            'level'      => 1,
                        ];

                        $insertData[] = $partyMember;
                        $userinfoData[] = $userinfo;
                    }
                }

                if (!empty($insertData)) {
                    $result = Db::name('user_party_member')->insertAll($insertData);
                    if (!$result) throw new \Exception("user_party_member 插入失败");
                }
                if (!empty($userinfoData)) {
                    $result = Db::name('user_userinfo')->insertAll($userinfoData);
                    if (!$result) throw new \Exception("user_userinfo 插入失败");
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('导入失败：' . $e->getMessage() . ' | File: ' . $e->getFile() . ' | Line: ' . $e->getLine());
                $this->error('导入失败：' . $e->getMessage());
            }
            $this->success('导入成功', '', ['user_party_member' => $insertData, 'user_userinfo' => $userinfoData]);
        }
        return $this->view->fetch();
    }





    /**
     * 下载导入模板
     */
    public function downloadTemplate()
    {
        // 模板文件的路径
        $filePath = ROOT_PATH . 'public/uploads/20250101/0a5ed5afaf38ba115cbe80fbc506bbab.xlsx';
        echo  $filePath;
        // 判断文件是否存在
        if (!file_exists($filePath)) {
            $this->error('模板文件不存在');
        }
        // 设置下载文件的头部信息
        // 获取文件名和 MIME 类型
        // $fileName = basename($filePath);
        // $fileMimeType = mime_content_type($filePath);
        // 设置响应头，手动返回下载
        return \fast\Http::sendToBrowser($filePath, false, true, '党员信息.xlsx');
    }
}
